// pages/setting/setting.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    settingInfo: ["我的信息"],
    avatarUrl: "",
    noAvatarUrl: "cloud://jiwu-5glbnwui4460186f.6a69-jiwu-5glbnwui4460186f-1312639486/noTouXiang.jpg",
    hasUserInfo: false,
    name: ""
  },

  //用户点击登录按钮，获取用户信息
  login: function (e) {
    wx.navigateTo({
      url: '../login/login',
    })
  },

  loginOut: function () {
    console.log("loginOut")
    wx.setStorageSync('user', null)
    wx.showToast({
      title: '退出成功!',
    })
    setTimeout(() => {
      this.setData({
        hasUserInfo: false,
        name: ""
      })
      this.onLoad()
    }, 1000);
  },

  bindtapHandler: function (e) {
    let user = wx.getStorageSync('user')
    let touch = e.target.id
    if (!user && typeof user != 'undefined' && user!=0) {
      wx.showToast({
        icon:"error",
        title: '请先登录',
      })
      return
    }
    else{
      wx.showToast({
        icon: "none",
        title: '您的账号是' + user.account,
      })
      return
    }
  },

  setImage: async function (path) {
    try{
      //将文件上传到云存储中  userProfile
      let uploadPath = await wx.cloud.uploadFile({
        cloudPath:'userProFile/userProFile.jpg',
        filePath:path
      })
      console.log(uploadPath)
      path = uploadPath.fileID
      let user = wx.getStorageSync('user')
      let account = user.account
      let res = await wx.cloud.database().collection("user").where({
        account: account,
      }).update({
        data: {
          path: path
        }
      })
      if (res.errMsg == "collection.update:ok") {
        this.setData({
          avatarUrl: path
        })
        //将图片存放到缓存中
        let userInfo = wx.getStorageSync('user')
        userInfo.path = path
        wx.setStorageSync('user', userInfo)
      }
    }catch(err){
      console.log(err)
    }
  },

  getImage: function (params) {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success: (res) => {
        let path = res.tempFiles[0].tempFilePath //获取图片路径
        this.setImage(path)
      }
    })
    //将头像信息放到缓存中
  },

  upLoad:async function(){
    wx.navigateTo({
      url:"../upload/uploadPage/uploadIndex"
     })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //从缓存中获取用户数据
    let userInfo = wx.getStorageSync('user')
    if (userInfo) {
      this.setData({
        hasUserInfo: true,
        name: userInfo.name,
        //如果用户没有设置头像，就是用默认头像
        avatarUrl: !userInfo.path ? "cloud://jiwu-5glbnwui4460186f.6a69-jiwu-5glbnwui4460186f-1312639486/touxiang.jpg" : userInfo.path
      })
    }
  },
})